/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package quanlysieuthi;
import DAO.CConfigDAO;
import DAO.CHistoryDAO;
import DAO.SubConfig;
import DTO.CConfig;
import DTO.CHistory;
import Model.CModel;
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import static quanlysieuthi.QuanLySieuThi.cfParams;
public class FrmConfig extends javax.swing.JFrame {

    /**
     * Creates new form FrmConfig
     */
    public FrmConfig() {
        initComponents();
        loadConFig();
    }
    List<CConfig>list = new ArrayList<CConfig>();
    CConfig cfCurrent = null;
    int currentIndex = 0, numberRow = 0;
    Boolean edit = false;
    
    private void setEdittable(Boolean b){
        this.txtthuong.setEditable(b);
        this.txtvalue.setEditable(b);
    }
    
    private void loadConFig(){
        CModel _model = new CModel(QuanLySieuThi.user_name);
        list = _model.getConfig();
        _model.Close();
        Vector<Vector> data = new Vector<Vector>();
        for(CConfig item : list){
            Vector<String> row = new Vector<String>();
            row.addElement(item.getMoTa());
            row.addElement(item.getValue());
            row.addElement(item.getType());
            data.add(row);
        }
        Vector<String> columnNames = new Vector<String>();
        columnNames.addElement("Diễn giải");
        columnNames.addElement("Giá trị");
        columnNames.addElement("Thưởng");
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        //tbldanhsach.
        this.tbldanhsach.removeAll();
        this.tbldanhsach.setModel(model);
        this.tbldanhsach.setFillsViewportHeight(true);
        this.tbldanhsach.setEnabled(false);
        this.numberRow = list.size();
        this.view(this.currentIndex);
        setEdittable(false);
    }
    
    private void view(int index){
        if(index >=0 && index <  this.numberRow){
            cfCurrent = this.list.get(index);
            this.txtmota.setText(cfCurrent.getMoTa());
            this.txtthuong.setText(cfCurrent.getType());
            this.txtvalue.setText(cfCurrent.getValue());
            this.txtRows.setText(String.format("%s/%s", this.currentIndex + 1,this.numberRow));
            this.tbldanhsach.setRowSelectionInterval(index, index);
        }
        else if(this.numberRow == 0){
            this.txtRows.setText(String.format("%0/%0"));
        }
    }
    
    
    private void editRow(){
        SubConfig config = SubConfig.getInstance();
        config.init();
        List<CHistory> lHistory = new ArrayList<CHistory>();
        CHistoryDAO historyDao = new CHistoryDAO();
        CConfigDAO cfDAO = new CConfigDAO();
        this.cfCurrent.setValue(this.txtvalue.getText().trim());
        this.cfCurrent.setType(this.txtthuong.getText().trim());
        List<CConfig>larrs = new ArrayList<CConfig>();
        larrs.add(cfCurrent);
        CHistory history = new CHistory();
        history.setChuc_nang("thay doi tham số hệ thống");
        history.setMota(cfCurrent.toString());
        history.setNguoiTao(QuanLySieuThi.user_name);
        lHistory.add(history);
        cfDAO.updates(larrs, config);
        historyDao.addrows(lHistory, config);             
        config.close();
        CModel _model = new CModel(QuanLySieuThi.user_name);
        QuanLySieuThi.cfParams = _model.setConfig();  
        _model.Close();
        loadConFig();
    }
    
    private void updates(){
        SubConfig config = SubConfig.getInstance();
        config.init();
        List<CHistory> lHistory = new ArrayList<CHistory>();
        CHistoryDAO historyDao = new CHistoryDAO();
        CConfigDAO cfDAO = new CConfigDAO();
        for(int i = 0;i < this.tbldanhsach.getRowCount();i++){
            CConfig item = this.list.get(i);
            String value = this.tbldanhsach.getModel().getValueAt(i, 1).toString();
            System.out.println("cot 1 : " + value);
            item.setValue(value);
            Object obj = this.tbldanhsach.getModel().getValueAt(i, 2);
            if(obj != null){
                item.setType(obj.toString());
            }
            CHistory history = new CHistory();
            history.setChuc_nang("thay doi tham số hệ thống");
            history.setMota(item.toString());
            history.setNguoiTao(QuanLySieuThi.user_name);
            lHistory.add(history);
        }//end for
        cfDAO.updates(list, config);
        historyDao.addrows(lHistory, config);             
        config.close();
        CModel _model = new CModel(QuanLySieuThi.user_name);
        QuanLySieuThi.cfParams = _model.setConfig();  
        _model.Close();
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbldanhsach = new javax.swing.JTable();
        btnEdit = new javax.swing.JButton();
        btnClose = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        txtmota = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtvalue = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtthuong = new javax.swing.JTextField();
        btnPrevAll = new javax.swing.JButton();
        btnPrev = new javax.swing.JButton();
        txtRows = new javax.swing.JTextField();
        btnNext = new javax.swing.JButton();
        btnNextAll = new javax.swing.JButton();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Tham số hệ thống"));

        tbldanhsach.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tbldanhsach.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbldanhsachMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbldanhsach);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 654, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 15, Short.MAX_VALUE))
        );

        btnEdit.setText("Sửa");
        btnEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });

        btnClose.setText("Thoát");
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(102, 102, 255));
        jLabel1.setText("CÀI ĐẶT HỆ THỐNG");

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        jLabel2.setText("Diễn giải");

        txtmota.setEditable(false);

        jLabel3.setText("Giá trị");

        jLabel4.setText("Thưởng");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtmota)
                    .addComponent(txtvalue)
                    .addComponent(txtthuong, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE))
                .addContainerGap(296, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtmota, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtvalue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtthuong, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(17, Short.MAX_VALUE))
        );

        btnPrevAll.setText("<<");
        btnPrevAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPrevAllActionPerformed(evt);
            }
        });

        btnPrev.setText("<");
        btnPrev.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPrevActionPerformed(evt);
            }
        });

        btnNext.setText(">");
        btnNext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNextActionPerformed(evt);
            }
        });

        btnNextAll.setText(">>");
        btnNextAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNextAllActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(194, 194, 194)
                .addComponent(jLabel1)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnPrevAll)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnPrev)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtRows, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnNext)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnNextAll))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnEdit)
                                .addGap(34, 34, 34)
                                .addComponent(btnClose)))
                        .addGap(205, 205, 205))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap(87, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnPrev)
                    .addComponent(btnPrevAll)
                    .addComponent(btnNext)
                    .addComponent(btnNextAll)
                    .addComponent(txtRows, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnClose)
                    .addComponent(btnEdit))
                .addContainerGap())
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
        // TODO add your handling code here:
        if(edit == false){
            this.edit = true;
            this.btnEdit.setText("Lưu");
            setEdittable(true);
        }
        else{
            this.edit = false;
            this.btnEdit.setText("Sửa");
            editRow();
            setEdittable(false);
        }
        
    }//GEN-LAST:event_btnEditActionPerformed

    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
    }//GEN-LAST:event_btnCloseActionPerformed

    private void tbldanhsachMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbldanhsachMouseClicked
        // TODO add your handling code here:
         JTable table =(JTable)evt.getSource();
        Point p = evt.getPoint();
        int rowIndex = table.rowAtPoint(p);
        if(rowIndex >=0 && rowIndex < list.size()){
            table.setRowSelectionInterval(rowIndex, rowIndex);
            cfCurrent = this.list.get(rowIndex);
            view(rowIndex);
        }
    }//GEN-LAST:event_tbldanhsachMouseClicked

    private void btnPrevAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrevAllActionPerformed
        // TODO add your handling code here:
        this.currentIndex = 0;
        this.view(currentIndex);
    }//GEN-LAST:event_btnPrevAllActionPerformed

    private void btnPrevActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrevActionPerformed
        // TODO add your handling code here:
        if(this.currentIndex > 0){
            this.currentIndex-=1;
            this.view(currentIndex);
        }
    }//GEN-LAST:event_btnPrevActionPerformed

    private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNextActionPerformed
        // TODO add your handling code here:
        if(this.currentIndex < this.numberRow){
            this.currentIndex+=1;
            this.view(currentIndex);
        }
    }//GEN-LAST:event_btnNextActionPerformed

    private void btnNextAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNextAllActionPerformed
        // TODO add your handling code here:
        this.currentIndex = this.numberRow - 1;
        this.view(currentIndex);
    }//GEN-LAST:event_btnNextAllActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmConfig.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmConfig.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmConfig.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmConfig.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrmConfig().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnNext;
    private javax.swing.JButton btnNextAll;
    private javax.swing.JButton btnPrev;
    private javax.swing.JButton btnPrevAll;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbldanhsach;
    private javax.swing.JTextField txtRows;
    private javax.swing.JTextField txtmota;
    private javax.swing.JTextField txtthuong;
    private javax.swing.JTextField txtvalue;
    // End of variables declaration//GEN-END:variables
}
